﻿/**
* CRL
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace CRL.Data.Dynamic
{
    internal partial class DynamicObjConvert
    {

        static dynamic getRow(List<string> columns,object[] values)
        {
            dynamic obj = new System.Dynamic.ExpandoObject();
            var dict = obj as IDictionary<string, object>;
            for (int i = 0; i < values.Count(); i++)
            {
                string columnName = columns[i];
                object value = values[i];
                dict.Add(columnName, value);
            }
            return obj;
        }
        public static List<dynamic> DataReaderToDynamic(IDataReader reader, out double runTime)
        {
            var time = DateTime.Now;
            List<dynamic> list = new List<dynamic>();
            var columns = new List<string>();
            for (int i = 0; i < reader.FieldCount; i++)
            {
                columns.Add(reader.GetName(i));
            }
            using (reader)
            {
                while (reader.Read())
                {
                    object[] values = new object[columns.Count];
                    reader.GetValues(values);
                    var d = DynamicObjConvert.getRow(columns, values);
                    list.Add(d);
                }
            }
            runTime = (DateTime.Now - time).TotalMilliseconds;
            return list;
        }
    }
    internal partial class DynamicObjConvert
    {
        public static async Task<List<dynamic>> DataReaderToDynamicAsync(IDataReader reader)
        {
            var time = DateTime.Now;
            List<dynamic> list = new List<dynamic>();
            var columns = new List<string>();
            for (int i = 0; i < reader.FieldCount; i++)
            {
                columns.Add(reader.GetName(i));
            }
            using (reader)
            {
                #region while
                while (await ((DbDataReader)reader).ReadAsync())
                {
                    object[] values = new object[columns.Count];
                    reader.GetValues(values);
                    var d = DynamicObjConvert.getRow(columns, values);
                    list.Add(d);
                }
                #endregion
            }
            var runTime = (DateTime.Now - time).TotalMilliseconds;
            return list;
        }
    }
}
